import logging
from logging import handlers
import config
import colorlog


def init_logger(file_path="./log/test.log", log_level=logging.DEBUG, when='midnight', interval=1, backupCount=3):
    """初始化日志工具"""
    if config.LOGGER is None:
        # 设置日志的输出格式
        log_format = "%(asctime)s|%(levelname)s|%(filename)s:%(funcName)s:%(lineno)d|-%(message)s"
        fmt = logging.Formatter(log_format)

        # 创建日志管理器
        file_handler = handlers.TimedRotatingFileHandler(file_path, when=when, interval=interval,
                                                         backupCount=backupCount, encoding="utf-8")
        console_handler = logging.StreamHandler()
        log_color_config = {
            "INFO":"green",
            "DEBUG":"white",
            "WARNING":"yellow",
            "ERROR":"red",
            "CRITICAL":"bold_red"
        }
        console_formatter = colorlog.formatter.ColoredFormatter(
            fmt= "%(log_color)s" + log_format,
            datefmt= "%Y-%m-%d %H:%M:%S",
            log_colors= log_color_config
        )
        # 日志管理器添加格式
        file_handler.setFormatter(fmt)
        console_handler.setFormatter(console_formatter)

        # 创建日志器
        logger = logging.getLogger("test")
        logger.setLevel(log_level)
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)


        config.LOGGER = logger
    return config.LOGGER

def print_logger(file_path="./log/test.log", log_level=logging.DEBUG, when='midnight', interval=1, backupCount=3):
    if config.LOGGER is None:
        # 设置日志的输出格式
        log_format = "%(asctime)s|%(levelname)s|-%(message)s"
        fmt = logging.Formatter(log_format)

        # 创建日志管理器
        file_handler = handlers.TimedRotatingFileHandler(file_path, when=when, interval=interval,
                                                         backupCount=backupCount, encoding="utf-8")
        console_handler = logging.StreamHandler()
        log_color_config = {
            "INFO":"green",
            "DEBUG":"white",
            "WARNING":"yellow",
            "ERROR":"red",
            "CRITICAL":"bold_red"
        }
        console_formatter = colorlog.formatter.ColoredFormatter(
            fmt= "%(log_color)s" + log_format,
            datefmt= "%Y-%m-%d %H:%M:%S",
            log_colors= log_color_config
        )
        # 日志管理器添加格式
        file_handler.setFormatter(fmt)
        console_handler.setFormatter(console_formatter)

        # 创建日志器
        logger = logging.getLogger("test")
        logger.setLevel(log_level)
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)


        config.LOGGER = logger
    return config.LOGGER

if __name__ == '__main__':
    logger = init_logger()
    logger.info("info")
    logger.debug("debug")
    logger.warning("waring")
    logger.error("error")
    logger.critical("critical")

